package com.yet.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.yet.center.ConfigCenter;
import com.yet.center.ZookeeperConfigCenter;
import com.yet.serialization.HessianSerialization;
import com.yet.serialization.Serialization;
import com.yet.source.SourceAutowireManager;

@Configuration
public class BeanConfiguration {

	@Value("${yet.config.connectString}")
	private String connectString;
	@Value("${yet.config.baseSleepTimeMs:1000}")
	private int baseSleepTimeMs;
	@Value("${yet.config.maxRetries:3}")
	private int maxRetries;

	public CuratorFramework curatorFramework() {
		return CuratorFrameworkFactory.newClient(connectString,
				new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries));
	}

	@Bean
	@ConditionalOnMissingBean(Serialization.class)
	public Serialization defaultSerialization() {
		return new HessianSerialization();
	}

	@Bean
	@ConditionalOnMissingBean(ConfigCenter.class)
	public ConfigCenter zookeeperConfigCenter(Serialization serialization) {
		ZookeeperConfigCenter zookeeperConfigCenter = new ZookeeperConfigCenter(curatorFramework(), serialization);
		zookeeperConfigCenter.start();
		return zookeeperConfigCenter;
	}

	@Bean
	public SpringAutowireHandler springAutowireHandler() {
		return new SpringAutowireHandler();
	}
	
	@Bean
	public SourceAutowireManager sourceAutowireManager() {
		return new SourceAutowireManager();
	}

}
